<template>
    <div>
        <el-container>
          <el-main class="m-content">
            <el-row :gutter="8">
              <el-col :span="8" v-for="image in imageList.list" :key="image.id">
                <el-card shadow="hover" :body-style="{ padding: '0px',minWidth: '220px' }">
                    <el-image
                      :src="image.imageUrl.split(',')[0]"
                      :preview-src-list="image.imageUrl.split(',')">
                    </el-image>

                  <div style="padding: 14px;">
                    <span>{{image.title}}</span>
                    <div class="bottom clearfix">
                      <el-popover v-if="image.userNickname"
                        placement="right"
                        trigger="hover">
                        <div v-if="image.userNickname">
                          <span>{{image.userNickname}}</span>
                          <span style="padding-left: 15px" v-if="$store.state.loggedIn && image.userId === $store.getters.getCurrentUserId">
                            <el-tag>Me</el-tag>
                          </span>
                          <span v-else>
                            <el-button @click="handleFollow(image.userId)" v-if="image.userNickname && $store.state.followingUserIdList.indexOf(image.userId)===-1" type="text" class="button">关注</el-button>
                            <el-button @click="handleFollow(image.userId)" v-if="image.userNickname && $store.state.followingUserIdList.indexOf(image.userId)!==-1" type="text" class="button">已关注</el-button>
                          </span>
                        </div>
                        <el-avatar v-if="image.userAvatar" :src="image.userAvatar" slot="reference"></el-avatar>
                      </el-popover>
                      <time class="time">{{ image.createdTime | dateFormat }}</time>
                      <el-button v-if="$store.state.collectedImageIdList.indexOf(image.id)===-1" @click="handleCollect(image.id)" type="text" icon="el-icon-star-off" class="button">收藏</el-button>
                      <el-button v-else @click="handleCollect(image.id)" type="text" icon="el-icon-star-on" class="button">已收藏</el-button>
                      <el-button @click="handleDownload(image.id, image.title)" type="text" icon="el-icon-download" class="button">下载</el-button>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-main>
        </el-container>
    </div>
</template>

<script>
export default {
  name: 'Gallery',
  components: {},
  props: {
    imageList: Object
  },
  data () {
    return {
      getCollectFlag: false
    }
  },
  filters: {
    dateFormat: function (value) {
      const date = new Date(value)
      // const y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? '0' + MM : MM
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let h = date.getHours()
      h = h < 10 ? '0' + h : h
      let m = date.getMinutes()
      m = m < 10 ? '0' + m : m
      return MM + '-' + d + ' ' + h + ':' + m
    }
  },
  methods: {
    handleUnlogined () {
      this.$confirm('登录后才能操作，去登陆?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push('/login')
      }).catch(() => {
      })
    },
    handleCollect (imageId) {
      // console.log(imageId)
      const userInfo = this.$store.getters.getUserInfo
      if (!userInfo) {
        this.handleUnlogined()
        return false
      }
      const userId = userInfo.id
      const params = new URLSearchParams()
      params.append('imageId', imageId)
      params.append('userId', userId)
      this.$axios.post('/collect_switch', params, {
        headers: {
          Authorization: this.$store.state.jwt
        }
      })
        .then(response => {
          // console.log(response.data)
          this.$store.commit('switch_collect', imageId)
        })
    },
    handleDownload (imageId, imageTitle) {
      // console.log(imageId)
      this.$axios.get('/images/download/' + imageId, {
        responseType: 'blob'
      }).then(response => {
        const fileName = imageTitle
        const data = response.data
        if (!data) return
        const blob = new Blob([data])
        if (window.navigator.msSaveOrOpenBlob) { // 兼容IE10
          navigator.msSaveBlob(blob, fileName + '.zip')
        } else { // 其他非IE内核支持H5的浏览器
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.zip')
          document.body.appendChild(link)
          link.click()
        }
      })
    },
    handleFollow (beFollowedId) {
      const userInfo = this.$store.getters.getUserInfo
      if (!userInfo) {
        this.handleUnlogined()
        return false
      }
      const subjectId = userInfo.id
      this.$axios.post('/follow/follow_switch', { subjectId, beFollowedId }, {
        headers: {
          Authorization: this.$store.state.jwt
        }
      })
        .then(response => {
          // console.log(response.data)
          this.$store.commit('switch_follow', beFollowedId)
        })
    }
  },
  mounted () {
    /**
     * 获取用户关注列表id和收藏图片集id，存储到vuex
     */
    if (this.$store.state.loggedIn) {
      // console.log('进入第一层')
      if (!this.getCollectFlag) {
        // console.log('用户已登录但未调用get collect')
        this.getCollectFlag = true
        const userId = this.$store.getters.getCurrentUserId
        this.$axios.get('/collect', { params: { userId } }).then(response => {
          this.$store.state.collectedImageIdList = response.data.data
          // console.log('获取collect')
          // console.log(this.$store.state.collectedImageIdList)
        })
        this.$axios.get('/follow/my_follow_ids', { params: { userId } }).then(response => {
          this.$store.state.followingUserIdList = response.data.data
        })
      }
    }
  }
}
</script>

<style scoped>

  .el-dropdown-link {
    cursor: pointer;
  }

  .el-row {
    margin-top: 20px;
  }

  .el-col {
    border-radius: 4px;
    margin-bottom: 15px;
  }
  /*内容样式*/
  .m-content{
    min-height: 900px;
    max-width: 900px;
    margin: 0 auto; /*居中*/
  }
  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .el-image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }
</style>
